<template>
  <van-form @submit="onSubmit">
    <van-field name="uploader">
      <template #label>
        <div class="custom-label">选择图片</div>
      </template>
      <template #input>
        <van-uploader v-model="uploadFiles" :max-count="1" @after-read="handleAfterRead"/>
      </template>
    </van-field>

    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { showFailToast, showSuccessToast } from 'vant';
import { updateUserAvatarUrl } from '../../api/User.ts';
import { useRouter } from "vue-router";
import {getCurrentUser} from "../../sevices/User.ts"; // 导入获取当前用户的API

const router = useRouter();
// 存储上传的文件信息
const uploadFiles = ref([]);
// 存储实际要提交的图片URL
const avatarUrl = ref('');
// 存储当前用户ID
const userId = ref<number | null>(null);

// 获取当前用户信息
const fetchCurrentUser = async () => {
  try {
    const result = await getCurrentUser();
    console.log('当前用户信息:', result);
    // @ts-ignore
    if (result) {
      userId.value = result?.id; // 获取用户ID
    } else {
      showFailToast('获取用户信息失败');
      router.back(); // 获取用户信息失败则返回
    }
  } catch (error) {
    console.error('获取用户信息出错:', error);
    showFailToast('网络错误，请稍后再试');
    router.back();
  }
};

// 钩子函数
onMounted(() => {
  fetchCurrentUser(); // 组件挂载时获取用户信息
});

// 处理文件上传后的回调
const handleAfterRead = (file: any) => {
  // 文件上传成功后，获取图片URL
  if (file.status === 'done') {
    // 根据van-uploader的文档，获取上传后的图片URL
    avatarUrl.value = file.response?.url || file.content || '';
    showSuccessToast('图片上传成功');
    console.log('图片URL:', avatarUrl.value);
  } else {
    showFailToast('图片上传失败');
  }
};

// 表单提交处理
const onSubmit = async () => {
  if (!avatarUrl.value) {
    showFailToast('请先上传图片');
    return;
  }

  if (!userId.value) {
    showFailToast('用户ID不存在');
    return;
  }

  try {
    // 调用API更新头像，传递userId和avatarUrl两个参数
    const result = await updateUserAvatarUrl(userId.value, avatarUrl.value);

    // @ts-ignore
    if (result.code === 0 && result.data) {
      showSuccessToast('修改用户头像成功');
      router.back(); // 返回上一页
    } else {
      // @ts-ignore
      showFailToast('修改用户头像失败' + (result.description ? `${result.description}` : ''));
    }
  } catch (error) {
    console.error('更新头像出错:', error);
    showFailToast('网络错误，请稍后再试');
  }
};
</script>